<template>
  <el-form :inline="true" :model="info" class="demo-form-inline">
    <el-form-item label="">
      <el-input v-model="info.organizeNameNo" placeholder="请输入组织编号/名称" />
    </el-form-item>
    <el-form-item label="" style="width: 200px;">
      <el-select
        v-model="info.organizeTypeNo"
        placeholder="请选择组织类型"
      >
        <el-option label="请选择" value="" />
        <el-option v-for="item in organizetype.a" :label="item.organizeTypeName" :value="item.organizeTypeNo" />
      </el-select>
    </el-form-item>
    <el-form-item label="" style="width: 200px">
      <el-select
        v-model="info.userNo"
        placeholder="请选择负责人"
      >
        <el-option label="请选择" value="" />
        <el-option v-for="item in user.a" :label="item.userName" :value="item.userNo" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="GetOrganize()">查询</el-button>
      <el-button type="" @click="Rest()">重置</el-button>
    </el-form-item>
  </el-form>
<el-form-item>
  <el-button type="success" @click="OpenAdd()">新增</el-button>
</el-form-item>
  <el-table :data="organize.a" border style="width: 100%">
    <el-table-column type="index" label="序号" width="60px"/>
    <el-table-column prop="organizeName" label="组织名称" />
    <el-table-column prop="organizeNo" label="组织编号" />
    <el-table-column prop="organizeTypeName" label="组织类型" />
    <el-table-column prop="userName" label="负责人" />
    <el-table-column prop="" label="操作" >
      <template v-slot="scope">
        <el-button type="primary" @click="OpenEdit(scope.row)">编辑</el-button>
        <el-button type="danger" @click="DeleteOrganize(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增组织 对话框 -->
  <el-dialog v-model="addDialogVisible" :title="dialogTitle" width="520px">
    <el-form ref="addFormRef" :model="addForm" label-width="96px">
      <el-form-item label="组织名称" prop="organizeName">
        <el-input v-model="addForm.organizeName" placeholder="请输入组织名称" />
      </el-form-item>
      <el-form-item label="组织编号" prop="organizeNo">
        <el-input v-model="addForm.organizeNo" placeholder="请输入组织编号" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="组织类型" prop="organizeTypeNo">
        <el-select v-model="addForm.organizeTypeNo" placeholder="请选择组织类型" style="width:100%">
          <el-option label="请选择" value="" />
          <el-option v-for="item in organizetype.a" :key="item.organizeTypeNo" :label="item.organizeTypeName" :value="item.organizeTypeNo" />
        </el-select>
      </el-form-item>
      <el-form-item label="父级组织">
        <el-select v-model="addForm.parentId" placeholder="请选择父级组织" style="width: 100%;" :disabled="isCompanySelected">
          <el-option label="请选择" value=""/>
          <el-option v-for="a in parentOptions" :key="a.organizeNo" :label="a.organizeName" :value="a.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="addSubmitting" @click="isEdit ? UpdateOrganize() : AddOrganize()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import {useCounterStore} from '@/stores/counter'
// @ts-ignore
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'
const store=useCounterStore();
const read = getReadClient(0)
const write = getWriteClient(0)
let organize:any=reactive({
    a:[]
})
let organizetype:any=reactive({
  a:[]
})
let user:any=reactive({
  a:[]
})
let info:any=reactive({
    organizeNameNo:'',
    organizeTypeNo:'',
    userNo:''
})

// 新增对话框与表单
const addDialogVisible = ref(false)
const addSubmitting = ref(false)
const addFormRef = ref()
const isEdit = ref(false)
const dialogTitle = ref('新增组织')
let addForm:any = reactive({
  id:'',
  organizeName:'',
  organizeNo:'',
  organizeTypeNo:'',
  parentId:'',
  userNo:''
})

// 是否选择了“公司”类型（基于字面值判断组织类型名称为“公司”）
const isCompanySelected = computed(() => {
  const current = organizetype.a.find((x:any)=> x.organizeTypeNo === addForm.organizeTypeNo)
  return current?.organizeTypeName === '公司'
})

// 根据所选类型动态过滤父级组织
const parentOptions = computed(()=>{
  // 选择公司：不可选择父级（控件禁用）；仍返回全部以便禁用时显示
  const current = organizetype.a.find((x:any)=> x.organizeTypeNo === addForm.organizeTypeNo)
  const typeName = current?.organizeTypeName
  if(typeName === '部门'){
    // 部门：父级只能是公司
    return (organize.a || []).filter((x:any)=> x.organizeTypeName === '公司')
  }
  if(typeName === '小组' || typeName === '项目组'){
    // 小组：父级只能是部门
    return (organize.a || []).filter((x:any)=> x.organizeTypeName === '部门')
  }
  return organize.a || []
})

// 当选择公司时，清空父级组织
watch(isCompanySelected, (val)=>{
  if(val){ addForm.parentId = '' }
})

// 若当前选择与父级不匹配，自动清空 parentId
watch(()=>addForm.organizeTypeNo, ()=>{
  const current = organizetype.a.find((x:any)=> x.organizeTypeNo === addForm.organizeTypeNo)
  const typeName = current?.organizeTypeName
  if(typeName === '部门'){
    const parent = (organize.a || []).find((x:any)=> x.organizeNo === addForm.parentId)
    if(parent && parent.organizeTypeName !== '公司') addForm.parentId = ''
  } else if(typeName === '小组' || typeName === '项目组'){
    const parent = (organize.a || []).find((x:any)=> x.organizeNo === addForm.parentId)
    if(parent && parent.organizeTypeName !== '部门') addForm.parentId = ''
  }
})
const GetOrganize=()=>{
    read({
        url:'sysread/api/Organize/GetOrganize',
        method:'get',
        params:{
            OrganizeNameNo:info.organizeNameNo,
            OrganizeTypeNo:info.organizeTypeNo,
            UserNO:info.userNo
        }
    })
    .then(res=>{
        organize.a=res.data.data
    })
    .catch(err=>{
        console.log(err);
    })
}
const GetOrganizeType=()=>{
  read({
    url:'sysread/api/Organize/GetOrganizeType',
    method:'get',
  })
  .then(res=>{
    organizetype.a=res.data.data
  })
}
const GetUser=()=>{
  read({
    url:'sysread/api/Organize/GetUser',
    method:'get',
  })
  .then(res=>{
    user.a=res.data.data
  })
}
const Rest=()=>{
  info.organizeTypeNo='',
  info.organizeNoName='',
  info.userNo=''
}

// 打开新增对话框
const OpenAdd = ()=>{
  isEdit.value = false
  dialogTitle.value = '新增组织'
  addForm.organizeName=''
  addForm.organizeNo=''
  addForm.organizeTypeNo=''
  addForm.parentId=''
  addForm.userNo=store.User.UserNo
  addDialogVisible.value=true
}

// 新增组织
const AddOrganize = ()=>{
  if(!addForm.organizeName){ return ElMessage.warning('请输入组织名称') }
  if(!addForm.organizeNo){ return ElMessage.warning('请输入组织编号') }
  if(!addForm.organizeTypeNo){ return ElMessage.warning('请选择组织类型') }

  addSubmitting.value = true
  write({
    url:'syswrite/api/Organize/AddOrganize',
    method:'post',
    data:addForm
  })
  .then(res=>{
    if(res.data.code==200){
      ElMessage.success('新增成功')
      GetOrganize()
      addDialogVisible.value=false
      addSubmitting.value=false
    }
    else{
      ElMessage.error(res.data.message)
    }
  })
}

// 打开编辑
const OpenEdit = (row:any)=>{
  isEdit.value = true
  dialogTitle.value = '编辑组织'
  addForm.id=row.id
  addForm.organizeName = row.organizeName
  addForm.organizeNo = row.organizeNo
  addForm.organizeTypeNo = row.organizeTypeNo || ''
  addForm.parentId = row.parentId || ''
  addDialogVisible.value = true
}

// 更新组织
const UpdateOrganize = ()=>{
  if(!addForm.organizeName){ return ElMessage.warning('请输入组织名称') }
  if(!addForm.organizeNo){ return ElMessage.warning('请输入组织编号') }
  addSubmitting.value = true
  write({
    url:'syswrite/api/Organize/UpdateOrganize',
    method:'post',
    data:addForm
  })
  .then(res=>{
    if(res.data.code==200){
      ElMessage.success('更新成功')
      addDialogVisible.value=false
      GetOrganize()
      addSubmitting.value=false
    }
    else{
      ElMessage.error(res.data.message);
    }
  })
}

// 删除组织
const DeleteOrganize = (row:any)=>{
  ElMessageBox.confirm(`确定删除“${row.organizeName}”吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(()=>{
    write({
      url:'syswrite/api/Organize/DeleteOrganize',
      method:'post',
      params:{
        Id:row.id
      }
    }).then((res)=>{
      if(res.data.code==200){
        ElMessage.success('删除成功')
        GetOrganize()
      }
      else{
        ElMessage.error(res.data.message)
      }
    })
  }).catch((err)=>{})
}
onMounted(()=>{
    GetOrganize();
    GetOrganizeType();
    GetUser();
})
</script>